<!--
 @description 经销商合作终止-编辑
 @fileName Add.vue
 @author zengqiongying
 @created 2023/04/18 20:46:23
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData" />
    </Card>
    <Card>
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="dealerData.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card title="经销商-合作终止信息">
      <Cell title="合作终止原因" is-column custom divider :right="false" required>
        <qmp-field v-model="cooperationEndDTO.reason" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
      <FieldPicker
        v-model="cooperationEndDTO.type"
        title="合作终止类型"
        :url="`/data-dict/app/v2/dictionary/CTM_COOPERATE_END_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        required
        @change="handleChangeType"
      />
      <FieldSelect
        v-if="cooperationEndDTO.type === 'C'"
        v-model="cooperationEndDTO.isTransferSales"
        title="是否转让销量"
        label-name="dictName"
        value-name="dictCode"
        :optionData="dictData.BOOLEANS"
        required
        clear
      />
      <FieldPicker
        v-if="cooperationEndDTO.type === 'C'"
        v-model="cooperationEndDTO.distributionType"
        title="未完成配送订单处理方式"
        :url="`/data-dict/app/v2/dictionary/CTM_TOBE_DISTRIBUTION_ORDER_PROCESS_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
        clear
      />
      <FieldPicker
        v-else
        v-model="cooperationEndDTO.distributionType"
        title="未完成配送订单处理方式"
        :url="`/data-dict/app/v2/dictionary/CTM_TOBE_DISTRIBUTION_ORDER_PROCESS_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        :excludes="['B']"
        required
        clear
      />
      <FieldSelect
        v-model="cooperationEndDTO.isRebateMaturity"
        title="装修返利是否到期"
        label-name="dictName"
        value-name="dictCode"
        :optionData="dictData.BOOLEANS"
        required
        clear
      />
      <FieldSelect
        v-model="cooperationEndDTO.isUnfulfilledOrder"
        title="是否有未交订货"
        label-name="dictName"
        value-name="dictCode"
        :optionData="dictData.BOOLEANS"
        required
        clear
      />

      <FieldSelect
        v-model="cooperationEndDTO.isUnfulfilledOrderSubmit"
        title="未交订货数量是否已提交"
        label-name="dictName"
        value-name="dictCode"
        :optionData="dictData.BOOLEANS"
        :required="[1, '1'].includes(cooperationEndDTO.isUnfulfilledOrder)"
        clear
      />
      <FieldSelect
        v-model="cooperationEndDTO.isDevelopNewCustomer"
        title="是否已开发新商家"
        label-name="dictName"
        value-name="dictCode"
        :optionData="dictData.BOOLEANS"
        required
        clear
      />
      <Cell
        v-if="[1, '1'].includes(cooperationEndDTO.isDevelopNewCustomer)"
        title="新商家概况描述"
        is-column
        custom
        divider
        :right="false"
        required
        subTitle="请从经销商年龄、经济实力、卖场选址地理位置、（预）报图面积、保证金缴纳等情况进行描述"
      >
        <qmp-field
          v-model="cooperationEndDTO.newCustomerDescribe"
          type="textarea"
          placeholder="输入内容"
          class="ctm-text-area"
        />
      </Cell>
      <Cell title="备注" is-column custom divider :right="false">
        <qmp-field v-model="cooperationEndDTO.remark" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card v-if="cooperationEndDTO.type === 'C'" title="经销商-门店数据">
      <!-- 合作终止类型为商家交接时显示 -->
      <OriginalStore ref="refOrginalStore" :changeCode="detail.code" :data-list="shopBusinessList" />
    </Card>

    <Card title="经销商-未完结的门店建设数据" v-if="shopConstructDTOS.length">
      <ShopConstructItem :list="shopConstructDTOS" :dictData="dictData" :readonly="false" />
    </Card>

    <Card v-if="decorateEnterpriseDTO && decorateEnterpriseDTO.code" title="经销商-关联轻居客户">
      <DisCustomerDeal v-model="decorateEnterpriseDTO" />
    </Card>
    <Card v-if="['A', 'B', 'C'].includes(cooperationEndDTO.type)" title="附件上传">
      <template v-if="cooperationEndDTO.type === 'A'">
        <Cell is-column custom title="最近一次整改通知书" :right="false" required>
          <AttachmentUpload v-model="attachment.ACCESS072" :objectId="id" type-code="ACCESS072" />
        </Cell>
      </template>
      <template v-if="cooperationEndDTO.type === 'B'">
        <Cell is-column custom title="自愿放弃说明书" :right="false" required>
          <AttachmentUpload v-model="attachment.ACCESS082" :objectId="id" type-code="ACCESS082" />
        </Cell>
        <Cell is-column custom title="商家手持身份证" :right="false" required>
          <AttachmentUpload v-model="attachment.ACCESS083" :objectId="id" type-code="ACCESS083" />
        </Cell>
        <Cell
          title="自愿放弃说明书模板下载"
          sub-title="（零售）经销商自愿放弃经营权说明书模板"
          is-column
          custom
          readonly
        >
          <AttachmentUpload v-if="templateFileList.ACCESS082.length" v-model="templateFileList.ACCESS082" readonly />
          <div v-else>暂无文件</div>
        </Cell>
        <Cell
          title="自愿放弃说明书签订指导下载"
          sub-title="（零售）经销商自愿放弃经营权说明书签订指导"
          is-column
          custom
          readonly
        >
          <AttachmentUpload v-if="templateFileList.ACCESS084.length" v-model="templateFileList.ACCESS084" readonly />
          <div v-else>暂无文件</div>
        </Cell>
      </template>

      <template v-if="cooperationEndDTO.type === 'C'">
        <Cell is-column custom title="交接证明" :right="false" required>
          <AttachmentUpload v-model="attachment.ACCESS085" :objectId="id" type-code="ACCESS085" />
        </Cell>
        <Cell
          v-if="['1', 1].includes(cooperationEndDTO.isTransferSales)"
          is-column
          custom
          title="关系证明"
          :right="false"
          :required="['1', 1].includes(cooperationEndDTO.isTransferSales)"
        >
          <AttachmentUpload v-model="attachment.ACCESS086" :objectId="id" type-code="ACCESS086" />
        </Cell>
        <Cell title="商家交接证明模板下载" sub-title="（零售）经销商交接证明模板" is-column custom readonly>
          <AttachmentUpload v-if="templateFileList.ACCESS085.length" v-model="templateFileList.ACCESS085" readonly />
          <div v-else>暂无文件</div>
        </Cell>
        <Cell
          title="交接双方现场签订照片"
          is-column
          custom
          :required="['1', 1].includes(cooperationEndDTO.isTransferSales)"
          :right="false"
        >
          <AttachmentUpload v-model="attachment.ACCESS111" type-code="ACCESS111" :objectId="detail.id" />
        </Cell>
        <Cell v-if="Object.keys(detail).length > 0" title="交接双方现场签订照片模板下载" is-column custom readonly>
          <AttachmentUpload v-if="templateFileList.ACCESS111.length" v-model="templateFileList.ACCESS111" readonly />
          <div v-else>暂无文件</div>
        </Cell>
      </template>
    </Card>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { ref, reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import FieldPicker from '@/components/FieldPicker/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import DisCustomerDeal from './components/DisCustomerDeal.vue'
  import ShopConstructItem from './components/ShopConstructItem.vue'
  import OriginalStore from './components/OriginalStore.vue'

  import { detail, saveCooperationEnd } from '@/apis/dealerMarketing/Termination'
  import { getDictList } from '@/apis/dataDict'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import { getAttachmentTemplate, queryAttachmentList } from '@/apis/common'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerInfoTerminationEdit',
    components: {
      Card,
      Cell,
      DealerCell,
      FieldSelect,
      FieldPicker,
      DisCustomerDeal,
      ShopConstructItem,
      OriginalStore,
      AttachmentUpload
    },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const refOrginalStore = ref()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        dictData: {
          BELONG_STAGE: [],
          BOOLEANS: [],
          CTM_SHOP_CONS_DATA_PROCESS_TYPE: []
        },
        detail: {},
        formData: {
          id: '',
          code: '', //单据编号
          isOtherReceiveManagerKnow: '',
          receiveManagerCode: '', // 接收客户经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeCode: '',
          receiveManagerTypeName: '',
          submitAnOpinion: ''
        },
        shopBusinessList: [], //门店数据信息(交接)
        shopConstructDTOS: [
          /* {
            shopName:'店名',
            belongStage:'所处阶段',
            handleType:'处理方式'
          } */
        ], //门店建设
        cooperationEndDTO: {
          changeCode: '',
          reason: '',
          type: '',
          distributionType: '',
          isRebateMaturity: '',
          isTransferSales: '',
          isUnfulfilledOrder: '',
          isUnfulfilledOrderSubmit: '',
          isDevelopNewCustomer: '',
          newCustomerDescribe: '',
          remark: ''
        }, // 终止合作处理

        decorateEnterpriseDTO: {
          code: '',
          name: '',
          cityLevelName: '',
          businessTypeName: '',
          cooperateStart: '',
          isTransferSales: '',
          isRebateMaturity: '',
          isUnfulfilledOrder: '',
          isUnfulfilledOrderSubmit: ''
        }, //经销商关联轻居客户
        attachment: {
          ACCESS072: [],
          ACCESS082: [],
          ACCESS083: [],
          ACCESS085: [],
          ACCESS086: [],
          ACCESS111: [] //交接现场签订照片
        }, // 附件
        templateFileList: {
          ACCESS082: [],
          ACCESS084: [],
          ACCESS085: [],
          ACCESS111: [] //交接双方现场签订照片模板下载
        }
      })
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const initFormData = (src: any, dst: any) => {
        for (const [k, v] of Object.entries(dst)) {
          let value = src[k]
          const isArry = v instanceof Array
          if (isArry && value) {
            value = value.split(',').filter((e: any) => !none.includes(e))
          }
          const isObj = Object.prototype.toString.call(v) === '[object Object]'
          dst[k] = value !== undefined && value !== null ? value : isArry ? [] : isObj ? {} : ''
        }
      }
      const initDictData = async () => {
        const BELONG_STAGE = await getDictList('BELONG_STAGE')
        const BOOLEANS = await getDictList('BOOLEANS')
        const CTM_SHOP_CONS_DATA_PROCESS_TYPE = await getDictList('CTM_SHOP_CONS_DATA_PROCESS_TYPE')
        datas.dictData.BELONG_STAGE = BELONG_STAGE || []
        datas.dictData.BOOLEANS = BOOLEANS || []
        datas.dictData.CTM_SHOP_CONS_DATA_PROCESS_TYPE = CTM_SHOP_CONS_DATA_PROCESS_TYPE || []
      }
      const getFormData = () => {
        const { formData, shopConstructDTOS, cooperationEndDTO, decorateEnterpriseDTO, attachment }: any = datas
        let data: anyObjectModle = {
          ...formData,
          cooperationEndDTO
        }
        if (shopConstructDTOS.length > 0) {
          data.shopConstructDTOS = shopConstructDTOS
        }

        if (decorateEnterpriseDTO && decorateEnterpriseDTO.code) {
          data.decorateEnterpriseDTO = decorateEnterpriseDTO
        }
        let attrFileList: any[] = []
        if (cooperationEndDTO.type === 'A') {
          attrFileList = [...attachment.ACCESS072]
        } else if (cooperationEndDTO.type === 'B') {
          attrFileList = [...attachment.ACCESS082, ...attachment.ACCESS083]
        } else if (cooperationEndDTO.type === 'C') {
          attrFileList = [...attachment.ACCESS085, ...attachment.ACCESS086, ...attachment.ACCESS111]
        }

        if (attrFileList.length > 0) {
          data.attachmentDTOS = attrFileList.map((v: any) => {
            return {
              ...v,
              ...{ modelId: data.id }
            }
          })
        }
        return data
      }

      const onSave = (schedule: string, callback: any) => {
        const data: anyObjectModle = getFormData()
        const { cooperationEndDTO } = datas
        const shopBusinessDTOS =
          cooperationEndDTO && cooperationEndDTO.type === 'C'
            ? (refOrginalStore.value && refOrginalStore.value.getDataList()) || []
            : [] //获取门店数据
        data.shopBusinessDTOS = shopBusinessDTOS || []
        if (data.shopConstructDTOS) {
          // 判断门店建设处理方式是否选择
          const flag = data.shopConstructDTOS.some((v: any) => {
            return none.includes(v.handleType)
          })
          if (flag) {
            proxy.$toast('请完善门店建设信息数据处理方式')
            return
          }
        }

        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            return
          }
          if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
            if (none.includes(data.receiveManagerCode)) {
              proxy.$toast('请选择接收客户经理')
              return
            }
          }

          if (data.cooperationEndDTO) {
            const d = data.cooperationEndDTO
            d.reason = `${d.reason}`.trim()
            d.newCustomerDescribe = `${d.newCustomerDescribe}`.trim()
            if (none.includes(d.reason)) {
              proxy.$toast('请输入合作终止原因')
              return
            }
            if (none.includes(d.type)) {
              proxy.$toast('请选择合作终止类型')
              return
            }

            if (d.type === 'C' && none.includes(d.isTransferSales)) {
              proxy.$toast('请选择是否转让销量')
              return
            }

            if (none.includes(d.distributionType)) {
              proxy.$toast('请选择未完成配送订单处理方式')
              return
            }

            if (none.includes(d.isRebateMaturity)) {
              proxy.$toast('请选择装修返利是否到期')
              return
            }

            if (none.includes(d.isUnfulfilledOrder)) {
              proxy.$toast('请选择是否有未交订货')
              return
            }

            if ([1, '1'].includes(d.isUnfulfilledOrder) && none.includes(d.isUnfulfilledOrderSubmit)) {
              proxy.$toast('请选择未交订货数量是否已提交')
              return
            }

            if (none.includes(d.isDevelopNewCustomer)) {
              proxy.$toast('请选择是否已开发新商家')
              return
            }

            if ([1, '1'].includes(d.isDevelopNewCustomer)) {
              if (none.includes(d.newCustomerDescribe)) {
                proxy.$toast('请输入新商家概况描述')
                return
              }
            } else {
              d.newCustomerDescribe = ''
            }
          }
          if (data.decorateEnterpriseDTO) {
            const d = data.decorateEnterpriseDTO

            if (none.includes(d.isTransferSales)) {
              proxy.$toast('关联轻居客户,请选择是否转让销量')
              return
            }
            if (none.includes(d.isRebateMaturity)) {
              proxy.$toast('关联轻居客户,请选择装修返利是否到期')
              return
            }

            if (none.includes(d.isUnfulfilledOrder)) {
              proxy.$toast('关联轻居客户,请选择是否有未交订货')
              return
            }

            if ([1, '1'].includes(d.isUnfulfilledOrder) && none.includes(d.isUnfulfilledOrderSubmit)) {
              proxy.$toast('关联轻居客户,请选择未交订货数量是否已提交')
              return
            }
          }
          const { cooperationEndDTO }: any = data
          if (cooperationEndDTO.type === 'C') {
            const { attachment }: any = datas
            if (!attachment.ACCESS085.length) {
              // 验证交接证明
              proxy.$toast('请上传交接证明')
              return
            }
            if (['1', 1].includes(cooperationEndDTO.isTransferSales)) {
              if (!attachment.ACCESS086 || attachment.ACCESS086.length === 0) {
                // 验证交接证明
                proxy.$toast('请上传关系证明')
                return
              }
              if (!attachment.ACCESS111 || attachment.ACCESS111.length === 0) {
                proxy.$toast('请上传交接双方现场签订照片')
                return
              }
            }
          } else {
            if (data.attachmentDTOS.length === 0) {
              proxy.$toast('请选择附件上传')
              return
            }
          }
        }

        data.schedule = schedule

        saveCooperationEnd(data).then((res: any) => {
          if (res.success === 1) {
            proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
            proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
            if (callback) {
              callback()
              return
            }
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }
      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerTermination/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }

      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail?.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('TerminationSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'TerminationSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }

      const getDetail = async () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          const d = res.data
          datas.detail = d
          initFormData(d, datas.formData)
          const tmpDTO: anyObjectModle = { changeCode: d.code }
          datas.shopBusinessList = d.shopBusinessDTOS || []
          datas.shopConstructDTOS = d.shopConstructDTOS || []
          datas.cooperationEndDTO = { ...datas.cooperationEndDTO, ...tmpDTO }
          datas.decorateEnterpriseDTO = { ...datas.decorateEnterpriseDTO, ...tmpDTO }
          if (d.cooperationEndDTO) {
            datas.cooperationEndDTO = { ...datas.cooperationEndDTO, ...d.cooperationEndDTO }
            // initFormData(d.cooperationEndDTO, datas.cooperationEndDTO)
          }
          if (d.decorateEnterpriseDTO && d.decorateEnterpriseDTO.code) {
            datas.decorateEnterpriseDTO = { ...datas.decorateEnterpriseDTO, ...d.decorateEnterpriseDTO }
          }
        })
      }
      const downTemplate = async () => {
        const codes = ['ACCESS082', 'ACCESS084', 'ACCESS085', 'ACCESS111']
        codes.forEach(async (code) => {
          const configId = await getAttachmentTemplate(code)
          if (configId) {
            const data = await queryAttachmentList(configId)
            datas.templateFileList[code] = data
          }
        })
      }
      const handleChangeType = (data: any) => {
        if (data.dictCode === 'C') {
          //商家交接  是否已开发新商家 选择是
          datas.cooperationEndDTO.isDevelopNewCustomer = 1
        } else {
          if (datas.cooperationEndDTO.distributionType === 'B') {
            datas.cooperationEndDTO.distributionType = ''
          }
        }
      }

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (!['DealerInfoTermination', 'DealerInfoTerminationDetail'].includes(toName)) {
          $store.commit('routerKeep/resetCache', instanceName)
        } else {
          $store.commit('routerKeep/removeCache', instanceName)
        }
      })
      downTemplate()
      initDictData()
      getDetail()
      return {
        ...toRefs(datas),
        dealerData,
        onView,
        onSave,
        onSearchCustomerManager,
        handleChangeType,
        refOrginalStore
      }
    }
  }
</script>
<style lang="less" scoped>
  .termination-add_edit {
    padding-top: 8px;
  }
</style>
